<template>
	<view>
		<view class="ticket__info f-dc">
			<z-paging ref="paging" :refresher-only="true" :auto="false" @query="GetWorkInfo">
				<template #top>
					<up-navbar :fixed="false" title="工单详情" :autoBack="true" :safeAreaInsetTop="true"
						leftIconColor="#fff">
					</up-navbar>
				</template>

				<!-- 主表card区域 -->
				<view class="common__box__form">
					<view class="common__box__form__card">
						<view class="common__box__form__card__title">
							<text>{{formData.BillNO}}</text>
						</view>

						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">产品信息：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.ProductName}}</text>
							</view>
						</view>

						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">计划开始时间：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.DueStartDate}}</text>
							</view>
						</view>
						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">计划结束时间：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.DueEndDate}}</text>
							</view>
						</view>

						<view class="common__box__form__card__field">
							<text class="common__box__form__card__field__label">工单进度：</text>
							<view class="common__box__form__card__field__value">
								<text>{{formData.WCQty}}</text>
								<text>/</text>
								<text>{{formData.FPlanQty}}</text>
								<text>{{formData.UnitName}}</text>
							</view>
						</view>

						<view v-show="showMFromore">
							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">生产车间：</text>
								<view class="common__box__form__card__field__value">
									<text>{{formData.FWorkshopName}}</text>
								</view>
							</view>

							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">是否线性：</text>
								<view class="common__box__form__card__field__value">
									<text>{{formData.IsLinear ? '是' : '否'}}</text>
								</view>
							</view>

							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">备注：</text>
								<view class="common__box__form__card__field__value">
									<text>{{formData.Comment || '-'}}</text>
								</view>
							</view>

							<view class="common__box__form__card__field">
								<text class="common__box__form__card__field__label">附件：</text>
								<view class="common__box__form__card__field__value">
									<view v-if="FilePathList.length"
										style="width: 100%;background-color: rgba(255,255,255,0.2);padding: 10rpx;border-radius: 20rpx;">
										<m-upload v-model="FilePathList" :add="false" :remove="false"
											:imageFormData="{compress:false}"
											:listStyle="{columns: BoxInfoCallBack.num,height:BoxInfoCallBack.height+'rpx',padding:'6px',columnGap:'10px',rowGap:'10px'}"
											cloudType="other"></m-upload>
									</view>

									<view v-else>-</view>
								</view>
							</view>
						</view>

						<!-- 箭头 -->
						<view class="common__box__form__card__more">
							<view class="x-c" @click="showMFromore=!showMFromore">
								<uni-icons :type="showMFromore ? 'up' : 'down'" size="20" color="#fff"></uni-icons>
							</view>

						</view>

					</view>
				</view>

				<!-- 吸顶Tab栏 -->
				<up-sticky>
					<up-tabs :list="TabList" :is-scroll="false" :current="tabCurrent" @change="clickHandler"
						activeStyle="color: #51d0d0;" :itemStyle="{height:'88rpx'}" lineColor="#51d0d0"
						:scrollable="false">
					</up-tabs>
				</up-sticky>


				<view class="ticket__info__content">

					<!-- 生产进度 -->
					<view class="ticket__info__content__list" v-show="tabCurrent == 0">
						<view class="ticket__info__content__list__card" v-for="(item,index) in ProgressList"
							:key="index">
							<view class="ticket__info__content__list__card__top">
								<view class="ticket__info__content__list__card__top__left">
									<view class="number__circle">
										<text>{{index+1}}</text>
									</view>

									<view class="ticket__info__content__list__card__top__left__title">
										<text>{{item.ProcedureName}}</text>
									</view>

									<up-tag v-if="item.Outsource" style="margin-left: 10rpx;" text="外协" size="mini"
										type="warning"></up-tag>
								</view>

								<view class="ticket__info__content__list__card__top__right">
									<view class="status_type"
										:style="{color:backColorByState(item).ModelColor,background:backColorByState(item).MenuBac}">
										<text>{{item.FStateName}}</text>
									</view>
								</view>
							</view>

							<view class="ticket__info__content__list__card__content">
								<view class="ticket__info__content__list__card__content__rowbox">
									<text>计划数</text>

									<text>{{item.FPlanQty}}</text>
								</view>
								<view class="ticket__info__content__list__card__content__rowbox">
									<text>良品数</text>

									<text>{{item.FDailyQtt}}</text>
								</view>
								<view class="ticket__info__content__list__card__content__rowbox">
									<text>不良数</text>

									<text>{{item.FNgQty}}</text>
								</view>


								<view class="ticket__info__content__list__card__content__rowbox">
									<template v-if="tabCurrent == 0">


										<m-progress-circle :progress="Number(item.ProgressNum)"
											:canvasId="'ticket_info'+String(index+1)" :radius="20" :lineWidth="2"
											:innerTextSize="12" :trackColor="backColorByState(item).ModelColor"
											:innerTextColor="backColorByState(item).ModelColor"
											:progressColor="backColorByState(item).ModelColor" :BottomTextSize="12">
										</m-progress-circle>
									</template>
								</view>

							</view>

						</view>
					</view>

					<!-- 用料明细 -->
					<view class="ticket__info__content__list" v-show="tabCurrent == 1">
						<view class="common__box__child__card" v-for="(item,index) in MaterialList" :key="index">
							<view class="common__box__child__card__top">
								<view class="common__box__child__card__top__left">
									<view class="number__circle">
										<text>{{index+1}}</text>
									</view>

									<view class="common__box__child__card__top__left__title">
										<text style="margin-left: 4rpx;">{{item.ProductCode}}</text>
									</view>
								</view>
							</view>

							<view class="common__box__child__card__content">
								<view class="common__box__child__card__content__field">
									<view class="common__box__child__card__content__field__label">
										<text>产品名称：</text>
									</view>
									<view class="common__box__child__card__content__field__value">
										<text>{{item.ProductName}}</text>
									</view>
								</view>
								<view class="common__box__child__card__content__field">
									<view class="common__box__child__card__content__field__label">
										<text>父件基数：</text>
									</view>
									<view class="common__box__child__card__content__field__value">
										<text>{{item.ParentNum}}</text>
									</view>
								</view>
								<view class="common__box__child__card__content__field">
									<view class="common__box__child__card__content__field__label">
										<text>子件用量：</text>
									</view>
									<view class="common__box__child__card__content__field__value">
										<text>{{item.SunNume}}</text>
									</view>
								</view>
								<view class="common__box__child__card__content__field">
									<view class="common__box__child__card__content__field__label">
										<text>损耗率：</text>
									</view>
									<view class="common__box__child__card__content__field__value">
										<text>{{item.LossRatio}}</text>
									</view>
								</view>
								<view class="common__box__child__card__content__field">
									<view class="common__box__child__card__content__field__label">
										<text>需领数量：</text>
									</view>
									<view class="common__box__child__card__content__field__value">
										<text>{{item.NeedQty}}</text>
									</view>
								</view>
								<view class="common__box__child__card__content__field">
									<view class="common__box__child__card__content__field__label">
										<text>最低需领数量：</text>
									</view>
									<view class="common__box__child__card__content__field__value">
										<text>{{item.LimitQty}}</text>
									</view>
								</view>
								<view class="common__box__child__card__content__field">
									<view class="common__box__child__card__content__field__label">
										<text>单位：</text>
									</view>
									<view class="common__box__child__card__content__field__value">
										<text>{{item.UnitName}}</text>
									</view>
								</view>

							</view>
						</view>
					</view>

					<!-- 生产履历 -->
					<view class="ticket__info__content__list common__box" v-show="tabCurrent == 2">
						<view class="common__box__process" v-for="(item,index) in HistoryList" :key="index">
							<view class="common__box__process__datebox">
								<view class="common__box__process__datebox__runtypebox">
									<view class="common__box__process__datebox__runtypebox__icon">
									</view>
								</view>
								<text class="common__box__process__datebox__runtypebox__datetext">{{item.date}}</text>
							</view>


							<view class="common__box__process__childbox">
								<view class="common__box__process__childbox__card" v-for="(row,ind) in item.ArrData"
									:key="ind">
									<view class="common__box__process__childbox__card__top">
										<view class="common__box__process__childbox__card__top__left">
											<u-tag :text="row.FType" plain></u-tag>

											<text class="titleText">{{row.EmplName}}</text>
											<text class="titleText">{{row.ProcedureName}}</text>
										</view>

										<view class="common__box__process__childbox__card__top__right">
											<text>{{row.Time}}</text>
										</view>
									</view>

									<view v-if="row.FType=='派工单'" class="common__box__process__childbox__card__content">
										<view>
											<text>派工数：</text>
											<text>{{row.FPlanQty}}</text>
										</view>
										<view>
											<text>完成数：</text>
											<text>{{row.WCQty}}</text>
										</view>
									</view>
									<view v-else class="common__box__process__childbox__card__content">
										<view>
											<text>良品数：</text>
											<text>{{row.FDailyQtt}}</text>
										</view>
										<view>
											<text>不良数：</text>
											<text>{{row.FNgQty}}</text>
										</view>
									</view>

								</view>

							</view>

						</view>
					</view>

				</view>

				<template #bottom>

					<view class="page__content__bottom" :style="uni.$utils.disposeSafeBottomFun()">

						<button v-if="FCJType == 1 && formData.Approve" @click="openDispatchBtn"
							class="content_bottom_primary_plainBtn page__content__bottom__btn">发放派工</button>
						<button @click="handleItemToDetail"
							class="content_bottom_primary_Btn page__content__bottom__btn">查看工单</button>
					</view>
				</template>
			</z-paging>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, computed, nextTick } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useUserStore, usePermissionStore, useTicketStore } from '@/store';

	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	const ticketStore = useTicketStore();
	// import mClUpload from '@/st_ticket/components/cl-upload/components/cl-upload/cl-upload'
	// import mClUpload from '@/commonPage/components/cl-upload/cl-upload';
	import mProgressCircle from '@/st_ticket/components/m-progress-circle/m-progress-circle'


	defineOptions({
		options: {
			styleIsolation: 'shared'
		}
	});
	let foundNode = ref<any>(null);
	// 获取页面按钮权限
	for (const module of permissionStore.moduleInfoAll) {
		if (module.TreeTypeName === '生产管理') {
			for (const node of module.Node) {
				if (node.APFunName === '新建工单') {
					foundNode.value = JSON.parse(JSON.stringify(node));
					break; // 找到后立即退出内层循环  
				}
			}
			if (foundNode.value) {
				break;
			}
		}
	}
	let btnApprove = ref<any>(null)
	btnApprove.value = uni.$utils.isEmpty(foundNode) ? [] : foundNode.value['IconApprove'];

	// 按钮映射
	function ApproveBack(str : string) {
		let Type = btnApprove.value.some((item : any) => {
			return item.MenuName == str
		})

		return Type;
	};


	const FCJType = computed(() => {
		return ticketStore.FCJType;
	})

	let WoOrderID = ref<any>(null);

	const ip_info = computed(() => {
		return mainStore.appConfigInfo.ICPServerIP;
	})
	let formData = reactive<any>({});
	// 生产进度列表
	let ProgressList = ref<any>([]);
	// 用料明细列表
	let MaterialList = ref<any>([]);
	// 生产履历列表
	let HistoryList = ref<any>([]);
	// 主表箭头
	let showMFromore = ref(false);

	// tab栏数据
	let TabList = [
		{
			name: '生产进度'
		},
		{
			name: '用料明细'
		},
		{
			name: '生产履历'
		}
	];
	let tabCurrent = ref(-1);
	function clickHandler(data : any) {
		tabCurrent.value = data.index;
	}

	interface pagingInstance {
		reload : () => void;
		refresh : () => void;
		complete : () => void;
		setLocalPaging : () => void;
		endRefresh : () => void;
	}
	let paging = ref<pagingInstance | any>(null);
	function isHttpUrl(str : any) {
		return str.startsWith("http://") || str.startsWith("https://");
	};
	let FilePathList = ref<any>([]);
	let BoxInfoCallBack = reactive({
		num: 3,
		height: 100
	});
	const screenWidth = mainStore.systemConfig.sysDeviceInfo.screenWidth;
	const backNumByWidth = uni.$utils.calculateAdaptiveLayout(screenWidth, 20);
	Object.assign(BoxInfoCallBack, backNumByWidth);

	function backColorByState(data : any) { // 根据工艺路线状态，返回对应颜色
		let ModelColor = null;
		let MenuBac = null;

		switch (data.FState) {
			case 0: // 未报工
				ModelColor = '#333';
				MenuBac = '#e7e7e7';
				break;
			case 1: // 已完成
				ModelColor = '#29c660';
				MenuBac = '#d9f7ed';
				break;
			case -1: // 指定完成
				ModelColor = '#d0d30b';
				MenuBac = '#fbffd7';
				break;
			case 2: // 已领料
				ModelColor = '#1696eb';
				MenuBac = '#adf0eb';
				break;
			case 3: // 部分报工
				ModelColor = '#1f93e1';
				MenuBac = '#daedfe';
				break;
			default:
				ModelColor = '#333';
				MenuBac = '#e7e7e7';
				break;
		}
		let obj = {
			ModelColor: ModelColor,
			MenuBac: MenuBac,
		}
		return obj;
	}

	async function GetWorkInfo() {

		try {


			const ret = await request({
				config: {
				},
				url: 'XGD_SelectWoOrder',
				method: 'POST',
				data: {
					WoOrderID: WoOrderID.value
				},
			});

			console.log(ret);
			if (ret.status == 200) {
				const childRet = await request({
					config: {
					},
					url: 'XGD_WorkOrder_PROC',
					method: 'POST',
					data: {
						WoOrderID: WoOrderID.value
					},
				});

				if (childRet.status == 200) {
					if (ret.data.ds[0].hasOwnProperty("Filepath") && !uni.$utils.isEmpty(ret.data.ds[0].Filepath)) {
						// 附件信息
						FilePathList.value = ret.data.ds[0].Filepath.split(',').map((item : any) => {
							return mainStore.getReadyStaticUrl(item);
						});
					};

					// 主表内容
					Object.assign(formData, ret.data.ds[0]);
					// console.log(formData);
					// 用料清单
					MaterialList.value = ret.data.ds2;
					// 生产进度
					ProgressList.value = childRet.data.ds.map((item : any) => {
						return {
							...item,
							ProgressNum: Number((+item.WCQty / +item.FPlanQty * 100).toFixed(2)) || 0,
							AwaitWorkQty: +item.FPlanQty - +item.FDailyQtt
						}
					});

					setTimeout(() => {
						paging.value.endRefresh();
					}, 100);
				} else {
					setTimeout(() => {
						paging.value.endRefresh();
					}, 100);
				};
			};

		} catch (error) {
			setTimeout(() => {
				paging.value.endRefresh();
			}, 100);
		}

	};

	function FileZeroBack(data : any) {
		let parts = data.split(' '); // 使用空格分割日期和时间部分
		let datePart = parts[0]; // 获取日期部分
		let timePart = parts[1]; // 获取时间部分
		let timeParts = timePart.split(':'); // 使用冒号分割时和分
		let hour = timeParts[0].padStart(2, '0'); // 补零处理小时部分
		let minute = timeParts[1].padStart(2, '0'); // 补零处理分钟部分
		return hour + ':' + minute;
	};
	// 获取生产履历
	function getTicketsHistory() {
		request({
			config: {
			},
			url: 'XGD_Traceability',
			method: 'POST',
			data: {
				WoOrderID: WoOrderID.value
			},
			success(ret : any) {
				// console.log(ret);
				if (ret.status == 200) {
					if (ret.data.ds.length) {
						const data = ret.data.ds;
						const dateMap = new Map<string, { date : string; ArrData : any[] }>(); // 使用Map作为映射表

						for (let i = 0; i < data.length; i++) { // for循环比forEach性能更好
							const item = data[i];
							// 提前处理日期，避免重复计算
							const billDate = item.BillDate;
							const dateKey = billDate.split(' ')[0];

							// 处理时间字段
							item.Time = FileZeroBack(billDate);

							// 从Map中获取已有数据（O(1)复杂度）
							let existingData = dateMap.get(dateKey);

							if (existingData) {
								existingData.ArrData.push(item);
							} else {
								const newEntry = { date: dateKey, ArrData: [item] };
								dateMap.set(dateKey, newEntry);
							}
						}

						// 将Map的值转换为数组
						// HistoryList.value = Array.from(dateMap.values());
						HistoryList.value = Array.from(dateMap.values()).map(item => ({
							...item,
							ArrData: item.ArrData.reverse()
						})).sort((a, b) => Number(new Date(b.date)) - Number(new Date(a.date)));
						// console.log(HistoryList.value);
					}


				}
			}
		});
	}



	// 按钮组事件
	function openDispatchBtn() {
		console.log(formData);
		ticketStore.createTicket_routing = {
			form: formData,
			ProgressList: ProgressList.value,
		};

		uni.navigateTo({
			url: '/st_ticket/page_dispatch/dispatch-create'
		})
	};

	let routes = getCurrentPages(); //当前页面栈
	const listenName = computed(() => {
		return 'ticket-info-page_' + routes.length
	})
	function handleItemToDetail() {
		uni.navigateTo({
			url: "/st_ticket/page_ticket/ticket-creat" + "?WoOrderID=" + WoOrderID.value + '&openListen=' + listenName.value
		})
	};


	onLoad((option : any) => {
		if (!uni.$utils.isEmpty(option)) {
			WoOrderID.value = option.WoOrderID;
			GetWorkInfo();
			getTicketsHistory();
		}
	});

	onMounted(() => {
		nextTick(() => {
			setTimeout(() => {
				tabCurrent.value = 0;
			}, 1000);
		})
	})
</script>

<style lang="scss">
	.u-sticky {
		background-color: #fff !important;
		top: 0 !important;
		box-shadow: 0 8px 11px -19px !important;
	}

	.u-tabs__wrapper__nav__item__text {
		padding: 8rpx 20rpx !important;
		font-size: 28rpx !important;
	}

	.ticket__info {

		height: 100vh;
		background-color: #f9f9f9;

		&__content {
			position: relative;

			&__list {
				padding: 10rpx 15rpx;

				&__card {
					padding: 15rpx;
					border-radius: 15rpx;
					background-color: #fff;
					position: relative;
					overflow: hidden;
					box-shadow: 0 0 8px -7px #333;
					margin-bottom: 15rpx;

					&__top {
						font-size: 26rpx;
						font-weight: 600;
						color: #000;
						display: flex;
						align-items: center;
						justify-content: space-between;

						&__left {
							display: flex;
							align-items: center;

							&__title {
								margin-left: 10rpx;
							}
						}

						&__right {
							display: flex;
							align-items: center;
							justify-content: flex-end;
						}
					}

					&__content {
						border-radius: 16rpx;
						background-color: #f7f7f7;
						padding: 20rpx 20rpx;
						margin-top: 20rpx;
						display: flex;
						align-items: center;
						justify-content: space-evenly;

						&__rowbox {
							font-size: 24rpx;
							display: flex;
							flex-direction: column;
							align-items: center;
							flex: 1;
							position: relative;

							text:last-child {
								margin-top: 10rpx;
							}

							&:last-child text:last-child {
								color: #e13a2b;
							}
						}




					}
				}
			}
		}
	}

	.common__box {
		padding: 20rpx;


		// 时间流程布局
		&__process {
			background-color: #fff;
			padding: 10rpx;

			// 时间轴区域
			&__datebox {
				display: flex;
				align-items: center;

				&__runtypebox {
					background-color: #c8eed5;
					width: 48rpx;
					height: 48rpx;
					border-radius: 9999px;
					justify-content: center;
					zoom: .6;
					display: flex;
					align-items: center;

					&__icon {
						background-color: #40d37d;
						width: 28rpx;
						height: 28rpx;
						border-radius: 9999px;
					}

					&__datetext {
						font-size: 24rpx;
						color: #999;
						margin-left: 8rpx;
					}
				}
			}

			&__childbox {
				padding: 20rpx;
				margin-bottom: 20rpx;
				background-color: #fff;
				min-height: 100rpx;

				&__card {
					margin-bottom: 20rpx;
					background-color: #f9f9f9;
					padding: 15rpx;

					&__top {
						display: flex;
						align-items: center;
						justify-content: space-between;

						&__left {
							display: flex;
							align-items: center;

							.titleText {
								font-weight: 600;
								color: #333;
								font-size: 24rpx;
								margin-left: 8px;
							}
						}

						&__right {
							font-size: 24rpx;
							color: #999;
						}
					}

					&__content {
						margin-top: 15rpx;
						padding: 8rpx 0;
						display: flex;
						align-items: center;
						font-size: 24rpx;
						padding-left: 30rpx;
						color: #999;

						&>view {
							margin-right: 15rpx;
						}
					}

				}
			}

		}

	}



	.status_type {
		width: fit-content;
		padding: 8rpx 20rpx;
		font-size: 24rpx;
		letter-spacing: 1px;
		color: #333;
		font-weight: 600;
		background-color: #e7e7e7;
		border-radius: 30rpx;
		zoom: 0.9;
	}
</style>